<template>
  <PageLayout full>
    <template #header>
      <HeaderLayout show-back :header-style="headerStyle">
        <view>{{ $t('TT.WaterSet.Title') }}</view>
      </HeaderLayout>
    </template>
    <view class="container">
      <PageTitle
        :title="$t('TT.WaterSet.Temp.Lable')"
        page-tip-image
        :temp="curTemp"
        :show-bar="(Number(curTemp) == 3276.7 && isMR120) || (Number(curTemp) == 120 && isMR100IRFEMS)"
        @show-page-tip="showPageTip"
      ></PageTitle>

      <view class="quick-temp">
        <view
          class="temp-fav"
          v-for="(item, index) in ProgramFavs"
          :key="index"
          :class="{ tempChoose: degrees[tempIndex].value == item.dataJson.value }"
          @click="selectFav(item.dataJson.value)"
        >
          <view class="temp-fav-text"
            ><text>{{ item.customName }}</text></view
          >
          <image
            v-if="degrees[tempIndex].value == item.dataJson.value"
            class="fav-close"
            :src="'/static/NoticeDissmissDark.png'"
            @click="delTempFav(item.id)"
          />
        </view>
        <view
          class="add-temp-fav add-temp-btn"
          :class="{ disabled: degrees[tempIndex].value > 50 }"
          @click="addTempFav"
        >
          <view class="add-temp-fav-plus">+</view>
          <view class="add-temp-fav-text">{{ $t('TT.WaterSet.AddFavorite.Button') }}</view>
        </view>
      </view>

      <ChooseTemp
        isUnit
        isGray
        removeZero
        :data="degrees"
        :cur-index="curIndex"
        @chooseTemp="chooseTemp"
        @pickState="changePickState"
      />

      <view class="quick-warm-up" style="visibility: hidden">
        <view class="warm-up-top-view">
          <view>{{ $t('TT.WaterSet.ZeroWater.Lable') }}</view>
          <switch color="#108ee9" :checked="coldwaterBtn" @clidk="changeColdWaterState" />
        </view>
        <view v-if="coldwaterBtn" class="warm-up-detail-view" @click="showQuickWarmUpPopView">
          <view class="warm-up-left-view">
            <view v-for="(item, index) in coldWaterTexts" :key="index" class="warm-up-left-text">
              <text style="line-height: 44rpx">{{ item }}</text>
            </view>
          </view>
          <view class="warm-up-right-Icon">
            <image src="@/pages/appliance/static/TT/ic_arrow_list1.png"></image>
          </view>
        </view>
      </view>

      <!-- 安全提示 -->
      <TopTips v-model:visible="temperatureProjectTips" :tips-content="$t('TT.WaterSet.Safe.Tips.Text')"></TopTips>
    </view>

    <template #footer>
      <FooterLayout :size="footerSize" :footer-style="footerStyle">
        <ActionButton :disabled="disabled" @click="optionConfirm">{{ $t('TT.WaterSet.Bottom.Button') }}</ActionButton>
      </FooterLayout>
    </template>

    <!-- 提示 -->
    <Modal
      v-model:visible="waterTips"
      :title="$t('TT.WaterSet.WaterTips.Dialog.Title')"
      :ok-text="$t('TT.WaterSet.WaterTips.Dialog.Ok.Button')"
    >
      <view class="water-set-tips" style="text-align: center">{{ waterTipsDes }}</view>
    </Modal>
    <!-- 温度收藏已达到上限 -->
    <Modal
      v-model:visible="waterFavFullVisible"
      :title="$t('TT.WaterSet.WaterTempFull.Dialog.Title')"
      :ok-text="$t('TT.WaterSet.WaterTempFull.Dialog.Ok.Button')"
    >
      <view class="water-set-tips">{{ saterFavFullTips }}</view>
    </Modal>
    <!-- 重命名 -->
    <RenameModal
      v-model:show="showAddFav"
      :title="$t('TT.WaterSet.Rename.Dialog.Title')"
      :ok-text="$t('TT.WaterSet.Rename.Dialog.Ok.Button')"
      :cancel-text="$t('TT.WaterSet.Rename.Dialog.Cancle.Button')"
      :name-focus="nameFocus"
      :nick-name="favName"
      @confirm="confirmFav"
    ></RenameModal>
    <!-- 删除收藏温度确认弹框 -->
    <Modal
      v-model:visible="delWaterVisible"
      :title="$t('TT.WaterSet.DelFav.Dialog.Title')"
      :description="$t('TT.WaterSet.DelFav.Dialog.Description.Text')"
      :cancel-text="$t('TT.WaterSet.DelFav.Dialog.Cancle.Button')"
      :ok-text="$t('TT.WaterSet.DelFav.Dialog.Ok.Button')"
      @ok="delTempFavText"
    >
    </Modal>
    <!-- EMS OTA升级弹框 -->
    <OtaUpgradeIRF :show="isMR100IRF || isMR100IRFEMS" :mcu-status="mcuStatus"></OtaUpgradeIRF>
  </PageLayout>
</template>
<script lang="ts">
export type SetSettingType = {
  settings: { key: string; value: string | number }[]
}
</script>
<script setup lang="ts">
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'
import netconfig from '@/config/netconfig'
import FooterLayout from '@/layout/page/footer.vue'
import ActionButton from '@/common/actionButton/actionButton.vue'
import PageTitle from '../components/pageTitle/pageTitle.vue'
import ChooseTemp from '../components/chooseTemp/chooseTemp.vue'
import Modal from '@/common/modal.vue'
import RenameModal from '@/common/renameModal.vue'
import TopTips from '@/common/topTips.vue'
import OtaUpgradeIRF from '../otaUpgrade/otaUpgradeIRF.vue'

import { footerStyle, footerSize } from '@/layout/appliance/style'
import { actionDebounce, showLoading, useEventReceiver } from '@/utils/mpHelper'
import type { TTController } from '@/controller/TT/definition'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import {
  setTTSetting,
  deleteProgramFavorite,
  getProgramFavorite,
  addProgramFavorite,
  type TTProgramFavoriteType,
} from '@/api/tt'
import { TT_SETTING_DHWSET, TT_SUMMER_BLMODE, TT_SUMMER_MODE } from '@/constants/Command'
import { TT_SETTING_BlDHWSet } from '../SmartAssistantTool'
import type { Remote } from '@/controller/base/types/remote'
import { useI18n } from 'vue-i18n'
import { safeTrack } from '@/dataReport/dataReportUtil'
import { TrackType, trackEvent } from '@/dataReport/tracks'

const i18n = useI18n()

const control = ref<TTController.Control | null>(null)
useEventReceiver('control', (received: TTController.Control) => {
  control.value = received
  listenMessages()
})

const headerStyle = {
  backgroundColor: '#fff',
}

let imgUrl = `${netconfig.ASSETSPRE_ICONS}`
const degrees = ref<{ value: number }[]>([])
for (let i = 35; i <= 60; i++) {
  degrees.value.push({
    value: i,
  })
}

const haId = ref('')
const isMR120 = computed(() => haId.value.indexOf('MR120') !== -1)
const isMR100IRF = computed(() => haId.value.split('-')[1] === 'MR100iRF10720')
const isMR100IRFEMS = computed(() => haId.value.split('-')[1] === 'MR100iRF10720EMS')

const curTemp = computed(() =>
  control.value?.store.waterTemp ? Number(control.value?.store.waterTemp) / 10 + '' : '0'
)
const waterTempSetInt = computed(() => control.value?.store.waterTempSetInt)
const blState = computed(() => control.value?.store.blState)
const BlDHWMax = computed(() => control.value?.store.BlDHWMax)
const mcuStatus = computed(() => control.value?.store.mcuStatus || 0)

const ProgramFavs = ref<TTProgramFavoriteType[]>([])
const curIndex = ref(0)
const tempIndex = ref(0)
const pickState = ref(false)
const disabled = ref(false)
const coldwaterBtn = ref(false)
const coldWaterTexts = ref([])
const showAddFav = ref(false)
const favName = ref('')
const nameFocus = ref(false)
const temperatureProjectTips = ref(false)
const waterFavFullVisible = ref(false)
const saterFavFullTips = ref('')
const delWaterVisible = ref(false)

watch(
  () => waterTempSetInt.value,
  (value) => {
    if (!value || degrees.value.length === 0) return
    degrees.value.forEach((item, index) => {
      if (item.value === Number(value)) {
        nextTick(() => {
          curIndex.value = index
          tempIndex.value = index
        })
      }
    })
  }
)
watch(
  () => BlDHWMax.value,
  (max) => {
    if (!max) return
    degrees.value = []
    for (let i = 35; i <= Number(max); i++) {
      degrees.value.push({
        value: i,
      })
    }
  }
)

onLoad((query: any) => {
  haId.value = query?.haId
  getProgramFav()
})

onUnload(() => {
  control.value?.remote.removeBatchObserves(observes)
})

/**
 * 获取收藏列表
 */
async function getProgramFav() {
  const res = await getProgramFavorite(haId.value)
  ProgramFavs.value = res.data || []
}
/**
 * 选择收藏温度
 */
function selectFav(curFavValue: number) {
  let newIndex = degrees.value.findIndex((item) => item.value === curFavValue)
  tipsDisabledFun(newIndex)
  curIndex.value = newIndex
  tempIndex.value = newIndex
}
/**
 * 点击删除收藏温度按钮
 */
const delFavId = ref(0)
function delTempFav(id: number) {
  delFavId.value = id
  delWaterVisible.value = true
}
/**
 * 确定删除收藏温度
 */
const delTempFavText = actionDebounce({
  call: async () => {
    const res = await deleteProgramFavorite(delFavId.value)
    if (res.code === 0) {
      getProgramFav()
      uni.showToast({
        title: i18n.t('APP.Common.DeleteSucess.Text'),
        icon: 'none',
      })
    }
  },
})
/**
 * 点击添加收藏温度
 */
function addTempFav() {
  safeTrack(() => {
    trackEvent('TT.WaterSet.AddFavorite.Button', {}, TrackType.ApplianceDetail)
  })
  let value = degrees.value[tempIndex.value].value
  if (value > 50) return
  favName.value = value + ''
  showAddFav.value = true
  nameFocus.value = true
}
function changeColdWaterState() {}
function showQuickWarmUpPopView() {}

/**
 * 选择温度
 * @param index
 */
function chooseTemp(index: number) {
  curIndex.value = index
  tempIndex.value = index
  tipsDisabledFun(index)
}
/**
 * 温度大于50时处理逻辑
 */
function tipsDisabledFun(index: number) {
  if (degrees.value[index].value > 50) {
    disabled.value = true
    temperatureProjectTips.value = true
  } else {
    disabled.value = false
    temperatureProjectTips.value = false
  }
}
/**
 * 滚动
 * @param state
 */
function changePickState(state: boolean) {
  pickState.value = state
}
/**
 * 点击确定
 */
const optionConfirm = actionDebounce({
  call: async () => {
    if (pickState.value) {
      uni.showToast({
        title: i18n.t('APP.Common.HandleQuick.Text'),
        mask: true,
        icon: 'none',
      })
      return
    }
    let params = {
      settings: [
        {
          key: 'BSH.Common.Setting.TlBl',
          value: 0,
        },
        {
          key: 'BSH.Common.Setting.TlRm',
          value: 0,
        },
        {
          key: TT_SETTING_DHWSET,
          value: degrees.value[tempIndex.value].value,
        },
      ],
    }

    if (isMR100IRF.value || isMR120.value || isMR100IRFEMS.value) {
      params = {
        settings: [
          {
            key: TT_SETTING_BlDHWSet,
            value: degrees.value[tempIndex.value].value,
          },
        ],
      }
    }
    await setSetting(params)
  },
})

/**
 * 下发设置指令
 * @param params
 */
async function setSetting(params: SetSettingType) {
  const res = await setTTSetting(haId.value, params)
  if (res.code === 0) {
    uni.showToast({
      title: i18n.t('APP.Common.SetSucess.Text'),
      icon: 'none',
    })
  }
}
/**
 * 显示生活热水提示框
 */
const waterTips = ref(false)
const waterTipsDes = ref('')
function showPageTip() {
  waterTips.value = true
  waterTipsDes.value = i18n.t('TT.WaterSet.WaterTips.Dialog.Content.Text')
}
/**
 * 确定收藏
 */
const confirmFav = actionDebounce({
  call: async (name: string) => {
    await changeFav(name)
  },
})
/**
 * 下发收藏指令
 * @param name
 */
async function changeFav(name: string) {
  let submitData = {
    key: TT_SETTING_DHWSET,
    value: degrees.value[tempIndex.value].value,
    customName: name,
  }
  const res = await addProgramFavorite(haId.value, submitData)
  if (res.code === 0) {
    hideModal()
    getProgramFav()
  } else if (res.code === 60017) {
    hideModal()
    waterFavFullVisible.value = true
    saterFavFullTips.value = i18n.t('TT.WaterSet.WaterTempFull.Dialog.Description.Text')
  } else {
    hideModal()
    waterFavFullVisible.value = false
    waterTips.value = true
    waterTipsDes.value = res.msg
  }
  safeTrack(() => {
    trackEvent(
      'TT.WaterSet.Rename.Dialog.Ok.Button',
      {
        ...submitData,
        successOrNot: res.code === 0,
        error_code: res.code,
        response_msg: res.msg,
      },
      TrackType.ApplianceDetail
    )
  })
}
/**
 * 隐藏弹框
 */
function hideModal() {
  favName.value = ''
  nameFocus.value = false
  showAddFav.value = false
}

/**
 * 监听
 */
const observes: Remote.BatchObserve<TTController.Store>[] = [
  {
    matcher: (msg) => [TT_SUMMER_MODE, TT_SUMMER_BLMODE].includes(msg.key),
    handler: (msg) => {
      if (Number(msg.value) === 1) {
        uni.navigateBack()
      }
    },
  },
]
function listenMessages() {
  control.value?.remote.addBatchObserves(observes)
}
</script>
<style scoped lang="less">
@import '@/styles/common.less';
@import '@/styles/switch.less';
.water-set-tips {
  font-weight: 400;
  font-size: 32rpx;
  line-height: 26px;
  color: var(--dark-color);
  opacity: 0.8;
  text-align: left;
}
.container {
  position: relative;

  .screenBox2 {
    padding-top: 0;
    height: 100%;
  }

  .quick-temp {
    margin: 48rpx 32rpx 32rpx;
    text-align: left;
    display: flex;
    flex-wrap: wrap;
  }

  .temp-fav {
    max-width: 340rpx;
    margin-right: 32rpx;
    position: relative;
    height: 64rpx;
    line-height: 64rpx;
    font-weight: 500;
    font-size: 28rpx;
    background: #f4f4f6;
    color: var(--dark-color);
    margin-bottom: 32rpx;
    text-align: center;
    padding: 0 20rpx;
    box-sizing: border-box;
    .temp-fav-text {
      width: 100%;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }
  }

  .tempChoose {
    background: var(--primary-color);
    color: #ffffff;
  }

  .fav-close {
    position: absolute;
    top: -13rpx;
    right: -13rpx;
    width: 28rpx;
    height: 28rpx;
  }

  .add-temp-fav {
    width: 240rpx;
    height: 64rpx;
    text-align: center;
    font-size: 28rpx;
    font-weight: 400;
    line-height: 64rpx;
    background: #f4f4f6;
    color: var(--dark-color);
    display: block;
    margin-bottom: 32rpx;
  }
  .add-temp-btn {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .add-temp-fav-plus {
    margin: -10rpx 10rpx 0 0;
    display: inline-block;
    font-size: 48rpx;
    vertical-align: middle;
    font-weight: 200;
  }

  .add-temp-fav-text {
    display: inline-block;
    vertical-align: middle;
  }

  /*收藏弹框*/

  .warmUpPopHeaderView {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    border-bottom: 0.5px solid #65758a;
    display: flex;
    justify-content: space-between;
  }

  .warmUpCancelButton {
    padding-left: 30rpx;
    font-family: PingFangSC-Regular;
    font-size: 28rpx;
    color: #ffffff;
  }

  .warmUpTitle {
    font-family: PingFangSC-Medium;
    font-size: 28rpx;
    color: #ffffff;
    text-align: center;
  }

  .warmUpConfirmButton {
    padding-right: 30rpx;
    font-family: PingFangSC-Regular;
    font-size: 28rpx;
    color: #42c18b;
  }

  .favCon {
    padding: 40rpx 32rpx 0;
    font-size: 32rpx;
    color: #fff;
    text-align: center;
    box-sizing: border-box;
  }

  .favDes {
    margin-bottom: 60rpx;
    width: 100%;
    line-height: 44rpx;
    display: inline-block;
  }

  .favEmbeded {
    padding: 0 18rpx;
    display: inline-block;
    width: auto;
    height: 40rpx;
    border-radius: 20rpx;
    border: 0.5px solid #b3bac4;
    line-height: 38rpx;
    text-align: center;
    box-sizing: border-box;
    font-size: 24rpx;
  }

  .favSingle {
    margin-bottom: 40rpx;
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
    min-height: 88rpx;
    line-height: 88rpx;
    box-sizing: border-box;
  }

  .favText {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 440rpx;
    height: 88rpx;
    line-height: 88rpx;
    border-radius: 12rpx;
    border: 0.5px solid #65758a;
    box-sizing: border-box;
    text-align: center;
  }

  .favTextDis {
    opacity: 0.3;
  }

  .favTextDis .titleName {
    color: #d9dde2;
  }

  .editFavBox {
    position: absolute;
    right: 20rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 60rpx;
    height: 60rpx;
  }

  .editFav {
    width: 30rpx;
    height: 30rpx;
  }

  .quick-warm-up {
    width: 650rpx;
    background: #3d56a1;
    border-radius: 12rpx;
    margin-left: 50rpx;
  }

  .warm-up-top-view {
    margin-left: 20rpx;
    margin-right: 20rpx;
    height: 88rpx;
    line-height: 88rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-family: PingFangSC-Regular;
    font-size: 32rpx;
    color: #ffffff;
    letter-spacing: -0.39px;
  }

  .warmUpButtonView {
    height: 100%;
    display: flex;
    align-items: center;
  }

  .warmUpButtonView image {
    width: 96rpx;
    height: 50rpx;
  }

  .warm-up-detail-view {
    margin-left: 20rpx;
    margin-right: 20rpx;
    padding-bottom: 22rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-family: PingFangSC-Regular;
    font-size: 32rpx;
    color: #bcc2cc;
    letter-spacing: 0;
    text-align: center;
  }

  .warm-up-left-view {
    width: 580rpx;
  }

  .warm-up-left-text {
    text-align: left;
  }

  .warm-up-right-Icon {
    height: 100%;
    display: flex;
    align-items: center;
  }

  .warm-up-right-Icon image {
    width: 16rpx;
    height: 26rpx;
  }

  .i-message {
    position: fixed;
    top: 0;
    width: 100%;
    height: 80rpx;
    z-index: 9999;
    opacity: 0.9;
    background: #4475d5;
    display: flex;
    align-items: center;
    padding: 20rpx 26rpx;
  }

  .imageclose {
    position: absolute;
    left: 0;
    width: 44rpx;
    height: 44rpx;
    padding-left: 25rpx;
  }

  .textdes {
    font-family: PingFangSC-Light;
    font-size: 28rpx;
    color: #ffffff;
    letter-spacing: -0.34px;
    padding: 20rpx 0rpx 20rpx 70rpx;
    line-height: 40rpx;
    box-sizing: border-box;
    max-width: 700rpx;
    text-align: left;
  }

  .textSmall {
    text-decoration: underline;
  }

  .hintArrow {
    display: inline-block;
    width: 28rpx;
    height: 28rpx;
    vertical-align: middle;
  }
}
</style>
